<template>
  <div>
    <table>
      <thead>
      <tr>
        <th>ID</th>
        <th>姓名</th>
        <th>年龄</th>
      </tr>
      </thead>
      <tbody>
      <tr v-for="user in currentPageData" :key="user.id">
        <td>{{ user.id }}</td>
        <td>{{ user.name }}</td>
        <td>{{ user.age }}</td>
      </tr>
      </tbody>
    </table>
    <div>
      <button @click="prevPage" :disabled="currentPage === 1">上一页</button>
      <span>{{ currentPage }} / {{ totalPages }}</span>
      <button @click="nextPage" :disabled="currentPage === totalPages">下一页</button>
    </div>
  </div>
</template>

<script setup>
import {ref, computed} from 'vue';

// 模拟所有用户数据
const allUsers = ref([
  {id: 1, name: '张三', age: 20},
  {id: 2, name: '李四', age: 22},
  {id: 3, name: '王五', age: 25},
  {id: 4, name: '赵六', age: 28},
  {id: 5, name: '孙七', age: 30},
  {id: 6, name: '周八', age: 32},
  {id: 7, name: '吴九', age: 35},
  {id: 8, name: '郑十', age: 38}
]);

// 每页显示的记录数
const itemsPerPage = 3;
// 当前页码
const currentPage = ref(1);

// 计算总页数
const totalPages = computed(() => Math.ceil(allUsers.value.length / itemsPerPage));

// 计算当前页的数据
const currentPageData = computed(() => {
  const startIndex = (currentPage.value - 1) * itemsPerPage;
  const endIndex = startIndex + itemsPerPage;
  return allUsers.value.slice(startIndex, endIndex);
});

// 上一页
const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--;
  }
};

// 下一页
const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++;
  }
};
</script>

<style scoped>
table {
  border-collapse: collapse;
  width: 100%;
}

th,
td {
  border: 1px solid #d42727;
  padding: 8px;
  text-align: left;
}

th {
  background-color: #41b387;
}
</style>